package cn.kailangtu.serialutils.modbus;

import cn.kailangtu.commontools.CommonUtils;
import cn.kailangtu.serialutils.HexUtil;
import cn.kailangtu.serialutils.api.SerialPortApi;

public class modbusUtil {
    public static byte[] writeToOne(int address,byte[] storage,byte[] value){
        //01 06 01 05 01 90 99 CB
        //01 06 01 05 01 90算出的值是99CB
        byte[] sendData = new byte[8];
        sendData[0] = (byte)(address & 0xFF);
        sendData[1] = 0x06;
        sendData[2] = storage[0];
        sendData[3] = storage[1];
        sendData[4] = value[0];
        sendData[5] = value[1];

        byte[] checkBytes = CRC16.getCheckCMDBytes( CRC16.calcCrc16(sendData,0,sendData.length-2));
        sendData[6] = checkBytes[0];
        sendData[7] = checkBytes[1];

        return sendData;
    }



    public static byte[] writeToMulti(int address,byte[] beginStorage,byte[] data)
    {

        byte 字节数 = (byte)data.length;
        byte[] 寄存器数 = CommonUtils.int2ByteArray( 字节数 / 2);
        byte[] sendData = new byte[data.length + 9];
        sendData[0] = (byte)(address & 0xFF);
        sendData[1] = 0x10;
        sendData[2] = beginStorage[0];
        sendData[3] = beginStorage[1];
        sendData[4] = 寄存器数[0];
        sendData[5] = 寄存器数[1];
        sendData[6] = 字节数;

        System.arraycopy(data,0,sendData,7,data.length);

        byte[] checkBytes = CRC16.getCheckCMDBytes( CRC16.calcCrc16(sendData,0,sendData.length-2));
        sendData[sendData.length-2] = checkBytes[0];
        sendData[sendData.length-1] = checkBytes[1];

        return sendData;
    }

    public static byte[] read(int address,byte[] storage,byte[] length)
    {
        byte[] sendData = new byte[8];
        sendData[0] = (byte)(address & 0xFF);
        sendData[1] = 0x03;
        sendData[2] = storage[0];
        sendData[3] = storage[1];
        sendData[4] = length[0];
        sendData[5] = length[1];

        byte[] checkBytes = CRC16.getCheckCMDBytes( CRC16.calcCrc16(sendData,0,sendData.length-2));

        sendData[6] = checkBytes[0];
        sendData[7] = checkBytes[1];

        return sendData;
    }

    public static byte[] read65(int address,byte[] storage,byte[] length)
    {
        byte[] sendData = new byte[8];
        sendData[0] = (byte)(address & 0xFF);
        sendData[1] = 0x65;
        sendData[2] = storage[0];
        sendData[3] = storage[1];
        sendData[4] = length[0];
        sendData[5] = length[1];

        byte[] checkBytes = CRC16.getCheckCMDBytes( CRC16.calcCrc16(sendData,0,sendData.length-2));

        sendData[6] = checkBytes[0];
        sendData[7] = checkBytes[1];

        return sendData;
    }
}
